/*
 * DataWindow.java
 *
 * Copyright (c) 2008 Sun Microsystems, Inc.
 *
 * Permission is hereby granted, free of charge, to any person obtaining a copy
 * of this software and associated documentation files (the "Software"), to
 * deal in the Software without restriction, including without limitation the
 * rights to use, copy, modify, merge, publish, distribute, sublicense, and/or
 * sell copies of the Software, and to permit persons to whom the Software is
 * furnished to do so, subject to the following conditions:
 *
 * The above copyright notice and this permission notice shall be included in
 * all copies or substantial portions of the Software.
 *
 * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
 * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
 * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
 * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
 * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
 * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER
 * DEALINGS IN THE SOFTWARE.
 */
package org.sunspotworld.demo;

import java.awt.Color;
import java.awt.Graphics;
import javax.swing.JFrame;

import java.text.DateFormat;
import java.util.Date;

/**
 * Create a new window to graph the sensor readings in.
 *
 * @author Ron Goldman
 */
public class DataWindow extends JFrame {

    private static final int MAX_SAMPLES = 100000;
    private int index = 0;
    private long[] time = new long[MAX_SAMPLES];
    private double[] val = new double[MAX_SAMPLES];
    DateFormat fmt = DateFormat.getDateTimeInstance();
    //////////////
    private static double Y_AMPL = 2;
    private int x_step;
    private static int X_RES = 25;   //number of samples in X_UNITS
    private static final int YTickSize = 30;   //size of the tick in pixels
    private static final int XTickSize = 50;   //size of the tick in pixels
    private static final int XTickNumber = 10;
    private double XOffset = 0;

    /*Time_step in ms */
    public DataWindow(String title, int time_step) {
        initComponents();
        setTitle(title);
        x_step = time_step;
    }

    public void addData(long t, double v) {
        time[index] = t;
        val[index++] = v;
        dataTextArea.append(fmt.format(new Date(t)) + "    value = " + v + "\n");
        dataTextArea.setCaretPosition(dataTextArea.getText().length());

        if(index > XTickNumber * X_RES) {
            time = new long[MAX_SAMPLES];
            val = new double[MAX_SAMPLES];
            index=0;
            XOffset+=XTickNumber*x_step * X_RES / 1000.0f;
        }

        repaint();
    }

    // Graph the sensor values in the dataPanel JPanel
    @Override
    public void paint(Graphics g) {
        super.paint(g);
        int left = dataPanel.getX();       // get size of pane
        int top = dataPanel.getY();
        int right = left + dataPanel.getWidth();
        int bottom = top + dataPanel.getHeight();

        //Coordinates of the graph inside the component, with margins
        int y0 = bottom - 15;
        int yn = top + 60;
        int x0 = left + 55;
        int xn = right - 20;
        int y_zero = yn + (y0 - yn) / 2;  //coordinate of 0 on the Y axis

        double vscale = (y_zero - y0) / (Y_AMPL);         //units per pixel
        double tscale = x_step * X_RES / 1000.0f;

        g.setColor(Color.BLACK);
        // X axis = time
        g.drawLine(x0, yn, x0, y0);         //draw Y axis
        // Y axis = sensor reading
        g.drawLine(x0, y_zero, xn, y_zero);         //draw X axis

        //System.out.println(x0+" "+y0+" "+xn+" "+yn+" "+(y0-yn)/2);



        for (int xt = x0 + XTickSize; xt < xn; xt += XTickSize) {
            g.drawLine(xt, y_zero + 5, xt, y_zero - 5);
            double value = XOffset + tscale * (xt - x0) / XTickSize;         //value of one tick
            value = (Math.rint(value * 100)) / 100.0; //round to 2 numbers after dot
            g.drawString(Double.toString(value), xt - (value < 10 ? 3 : 7), y_zero + 20);
        }


        g.setColor(Color.BLUE);

        for (int i = 1; i <= (y0 - y_zero) / YTickSize; i++) {
            double value = (i * YTickSize) / vscale;
            value = (Math.rint(value * 100)) / 100.0; //round to 2 numbers after dot
            g.drawLine(x0 - 5, y_zero + i * YTickSize, x0 + 5, y_zero + i * YTickSize);
            g.drawString(Double.toString(value), x0 - 43, y_zero + i * YTickSize);

            g.drawLine(x0 - 5, y_zero - i * YTickSize, x0 + 5, y_zero - i * YTickSize);
            g.drawString(Double.toString(-value), x0 - 38, y_zero - i * YTickSize);
        }

        // graph sensor values
        int xp = -1;
        int vp = -1;
        //System.out.println("\nZaczynamy rysowac");
        for (int i = 0; i < index; i++) {
            int x = x0 + (int) (((double) XTickSize / X_RES) * ((time[i] - time[0]) / x_step));
            int v = y_zero + (int) (val[i] * vscale);
            //System.out.println("" + (time[i] - time[0]) + " -> " + x);
            if (xp > 0) {
                g.drawLine(xp, vp, x, v);
            }
            xp = x;
            vp = v;
        }
    }

    /** This method is called from within the constructor to
     * initialize the form.
     * WARNING: Do NOT modify this code. The content of this method is
     * always regenerated by the Form Editor.
     */
    @SuppressWarnings("unchecked")
    // <editor-fold defaultstate="collapsed" desc="Generated Code">//GEN-BEGIN:initComponents
    private void initComponents() {

        dataPanel = new javax.swing.JPanel();
        jScrollPane1 = new javax.swing.JScrollPane();
        dataTextArea = new javax.swing.JTextArea();

        setMinimumSize(new java.awt.Dimension(400, 400));

        dataPanel.setBackground(new java.awt.Color(255, 255, 255));
        dataPanel.setMinimumSize(new java.awt.Dimension(400, 250));
        dataPanel.setPreferredSize(new java.awt.Dimension(400, 250));
        getContentPane().add(dataPanel, java.awt.BorderLayout.CENTER);

        jScrollPane1.setVerticalScrollBarPolicy(javax.swing.ScrollPaneConstants.VERTICAL_SCROLLBAR_ALWAYS);
        jScrollPane1.setMinimumSize(new java.awt.Dimension(400, 100));
        jScrollPane1.setPreferredSize(new java.awt.Dimension(400, 100));

        dataTextArea.setColumns(20);
        dataTextArea.setEditable(false);
        dataTextArea.setRows(4);
        jScrollPane1.setViewportView(dataTextArea);

        getContentPane().add(jScrollPane1, java.awt.BorderLayout.SOUTH);

        pack();
    }// </editor-fold>//GEN-END:initComponents
    // Variables declaration - do not modify//GEN-BEGIN:variables
    private javax.swing.JPanel dataPanel;
    private javax.swing.JTextArea dataTextArea;
    private javax.swing.JScrollPane jScrollPane1;
    // End of variables declaration//GEN-END:variables
}
